package com.demoworld;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by francis on 2017/6/18.
 * 测试在redis中执行lua脚本
 */
public class ScriptTest {
    public static String scripts = "local string_plit =  function (szFullString, szSeparator)\n" +
            "\tlocal nFindStartIndex = 1\n" +
            "\tlocal nSplitIndex = 1\n" +
            "\tlocal nSplitArray = {}\n" +
            "\twhile true do  \n" +
            "\t   local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)  \n" +
            "\t   if not nFindLastIndex then  \n" +
            "\t    nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))  \n" +
            "\t    break\n" +
            "\t   end\n" +
            "\t   nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)  \n" +
            "\t   nFindStartIndex = nFindLastIndex + string.len(szSeparator)  \n" +
            "\t   nSplitIndex = nSplitIndex + 1  \n" +
            "\tend\n" +
            "\treturn nSplitArray\n" +
            "end\n" +
            "\n" +
            "local get_by_keys = function (keys)\n" +
            "  local result = {}\n" +
            "  local keys_arr = string_plit(keys, ',')\n" +
            "  for i, v in ipairs(keys_arr) do\n" +
            "  \tlocal value = redis.call('get', v)\n" +
            "  \ttable.insert(result, value)\n" +
            "  end\n" +
            "  return result\n" +
            "end\n" +
            "\n" +
            "local cache_keys = KEYS[1]\n" +
            "return get_by_keys(cache_keys)";

    public static String strSHA = "";

    static {
        strSHA = CacheHelper.INSTANCE.loadScript(ScriptTest.scripts);
    }

@Test
public void test1() {
    CacheHelper.INSTANCE.set("a", "a");
    CacheHelper.INSTANCE.set("b", "b");
    CacheHelper.INSTANCE.set("c", "c");
    String[] params = new String[3];
    Object tmpObj = CacheHelper.INSTANCE.evalSHA(strSHA, "a,b,c");
    List<String> tmpList = (ArrayList<String>) tmpObj;
    tmpList.forEach(x -> {
        System.out.println(x);
    });
}

    @Test
    public void test() {
        CacheHelper.INSTANCE.set("a", "a");
        CacheHelper.INSTANCE.set("b", "b");
        CacheHelper.INSTANCE.set("c", "c");
        String[] params = new String[3];
        Object tmpObj = CacheHelper.INSTANCE.eval(scripts, "a,b,c");
        List<String> tmpList = (ArrayList<String>) tmpObj;
        tmpList.forEach(x -> {
            System.out.println(x);
        });
    }
}
